package com.jayson.server.catalina;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 映射类
 * 保存端口号和对应的虚拟主机列表
 */
public class Mapper {

    private Map<String, List<Host>> portMap = new HashMap<>();

    public Map<String, List<Host>> getPortMap() {
        return portMap;
    }

    /**
     * 解析server.xml 配置文件，并封装到mapper中
     * @param path
     * @throws DocumentException
     */
    public void init(String path) throws DocumentException {
        InputStream resourceAsStream = Mapper.class.getClassLoader().getResourceAsStream(path);
        SAXReader reader = new SAXReader();
        Document document = reader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
        List<Element> serviceEList = rootElement.selectNodes("Service");
        serviceEList.forEach((serviceElement) -> {
            Element connectorElement = (Element) serviceElement.selectSingleNode("Connector");
            String port = connectorElement.attributeValue("port");

            List<Element> engineEList = serviceElement.selectNodes("Engine");
            List<Host> hostList = new ArrayList<>();
            engineEList.forEach((engineElement) -> {
                hostList.addAll(getHostList(engineElement));
            });

            portMap.put(port, hostList);
        });

        for(String key : portMap.keySet()){
            List<Host> hostList = portMap.get(key);
            hostList.forEach((host) -> {
                host.init();
            });
        }
    }

    /**
     * 获取虚拟主机集合
     * @param engineElement
     * @return
     */
    private List<Host> getHostList(Element engineElement) {
        List<Host> hostList = new ArrayList<>();
        List<Element> hostEList = engineElement.selectNodes("Host");
        hostEList.forEach((hostElement) -> {
            String name = hostElement.attributeValue("name");
            String appBase = hostElement.attributeValue("appBase");
            hostList.add(new Host(name, appBase));
        });
        return hostList;
    }
}
